package com.dude.screens;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import com.dude.R;
import com.dude.R.id;
import com.dude.R.layout;
import com.dude.interfaces.IMemoryService;
import com.dude.objects.GenericPair;
import com.dude.objects.ProfilesArrayAdapter;
import com.dude.utils.FilesOperations;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;


/**
 * profiles screen - shows a list of the names of all objects' profiles in the file system
 */
public class Profiles extends Activity
{

	/*----- name of shared preferences, to be passed along in the intent --- */ 
	public static final String isNewProfile = "isNewProfile";
	public static final String profileName = "profileName";
	
	//============= widgets====================================
	protected ListView lv ;
	private MenuItem deleteSinglesMenu;
	private MenuItem deleteMultiMenu;

	//===================global variables======================
	protected ArrayList<String> singleObjectsNames;
	protected ArrayList<String> multiObjectsNames;
	protected ArrayList<GenericPair<String, Boolean>> objectsList;
	protected ArrayAdapter<GenericPair<String, Boolean>> adapterObjects;	
	protected IMemoryService fo;

	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.profiles);
		// get the names of all profiles in the system
		fo  = new FilesOperations(this);
        singleObjectsNames = new ArrayList<String>();
        multiObjectsNames = new ArrayList<String>();
		if (!fo.getAllObjectsNames(singleObjectsNames, multiObjectsNames))
		{
        	createErrorDialog("Retrieving Existing Objects' Names Failed ");
        	// close the Activity:
        	Profiles.this.finish();
		}
		// sort all object names lexically in objectsList
		objectsList = new ArrayList<GenericPair<String, Boolean>>();
		sortObjectsNames();
				
		// prepare the list
		lv = (ListView)findViewById(R.id.profile_objects_list);	
		//create adapter
		adapterObjects = new ProfilesArrayAdapter(Profiles.this, objectsList);	
		lv.setAdapter(adapterObjects);
			
		// listening to click on item of single objects' list
		lv.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parent, View view, int position, long id){				
				//get the selected item
	            String profile = objectsList.get(position).getFirst();	            
	            //Launching new Activity on selecting a single List Item	            
	            // check by position if single or multi
	            if (objectsList.get(position).getSecond()) // if (true) the object is single
	            {
		            Intent i = new Intent(Profiles.this, ExtendedSingleProfile.class);
		            i.putExtra(profileName, profile);
		            i.putExtra(isNewProfile, false);
		            startActivity(i);	 
	            }
	            else
	            {
		            Intent i = new Intent(Profiles.this, ExtendedMultiObject.class);
		            i.putExtra(profileName, profile);
		            i.putExtra(isNewProfile, false);
		            startActivity(i);	 
	            }	                        
			}			 
		 });
				
	}
	
	
    protected void onResume()
    {   	
    	super.onResume();   	
    	//refresh the list of objects on display
    	updateScreen();
    }
	
    
    protected void updateScreen()
    {
    	objectsList.clear();
    	singleObjectsNames.clear();
    	multiObjectsNames.clear();
		if (!fo.getAllObjectsNames(singleObjectsNames, multiObjectsNames))
		{
        	createErrorDialog("Retrieving Existing Objects' Names Failed ");
        	// close the Activity:
        	Profiles.this.finish();
		}
		sortObjectsNames();

		adapterObjects = new ProfilesArrayAdapter(Profiles.this, objectsList);
		lv.setAdapter(adapterObjects);
    }
	
    
    /* the method shows an alarm dialog with msg explaining the error
     * 
     */
    protected void createErrorDialog(String msg)
    {
    	AlertDialog.Builder builder = new AlertDialog.Builder(this);
    	builder.setTitle("Error ");
    	builder.setMessage(msg);
    	builder.setCancelable(true);
    	builder.setPositiveButton(" OK ", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog,int id) {
				dialog.cancel();			
			}
		  });
    	
    	//create the dialog
    	AlertDialog dialog = builder.create();
    	dialog.show();
    }
    
    /* put all the names in singleObjectsNames and multiObjectsNames in objectsList, in sorted
     * order, and with fitting boolean value indicating if the name is of a single or a multi object.
     */
    protected void sortObjectsNames()
    {
    	// fill objectsList with all elements of both single and multi objects
    	for (String s : singleObjectsNames)
    		objectsList.add(new GenericPair<String, Boolean>(s, true));
    	for (String s : multiObjectsNames)
    		objectsList.add(new GenericPair<String, Boolean>(s, false));
    	// sort objectsList
    	Collections.sort(objectsList, new Comparator<GenericPair<String, Boolean>>(){
			public int compare(GenericPair<String, Boolean> object1,
					GenericPair<String, Boolean> object2) {
				return object1.getFirst().compareTo(object2.getFirst());
			}  		
    	});   	  	
    }
    
    
    // when user clicks the menu button he sees options to delete all single objects and delete
    // all multi objects
 	@Override
 	public boolean onCreateOptionsMenu(Menu menu) {
 		deleteSinglesMenu = menu.add("Delete all single objects");
 		deleteMultiMenu = menu.add("Delete all multi objects");
 		return true;
 	}

 	// change the current view mode 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	if (item == deleteSinglesMenu)
    		if (!fo.deleteAllSingleObjects())
    		{
    			createErrorDialog("Deletion of all single objects failed");
    			return true;
    		}   		
    	if (item == deleteMultiMenu)
    		if (!fo.deleteAllMultiObjects())
    		{
    			createErrorDialog("Deletion of all multi objects failed");
    			return true;
    		}
    	if ((item == deleteSinglesMenu)||(item == deleteMultiMenu))
    		updateScreen();
    	
    	return true;
    }


    
    
}
